package com.zhangxin.aiInterview.manager.work_flow.debug_code;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 调试编程题代码
 */
public class DebugCode {

    // 替换为你的API Key 和 API Secret
    private static final String API_KEY = "cd5245ddf5444cfcedd25b57a29b4c0b";
    private static final String API_SECRET = "MzdhNDEzNzVkMDcyZDhhZTM3MWNjODhj";
    private static final String FLOW_ID = "7325123644665229312";  // 工作流 ID


    /**
     * 简历内容提取
     *
     * @param codeModel 调试的代码（包括代码，语言，描述）
     */
    public static String debugCode(String codeModel) {

        StringBuilder result = new StringBuilder();
        try {
            // 1. 构建请求体 JSON（使用 Hutool）
            JSONObject parameters = new JSONObject();
            parameters.put("AGENT_USER_INPUT", codeModel);

            JSONObject requestBody = new JSONObject();
            requestBody.put("flow_id", FLOW_ID);
            requestBody.put("uid", "123");
            requestBody.put("stream", true);
            requestBody.put("parameters", parameters);

            // 2. 构建请求 URL
            URL url = new URL("https://xingchen-api.xf-yun.com/workflow/v1/chat/completions");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 3. 设置请求方法和头部
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            // 设置 Authorization
            String authorizationHeader = "Bearer " + API_KEY + ":" + API_SECRET;
            connection.setRequestProperty("Authorization", authorizationHeader);
            connection.setDoOutput(true);
            // 4. 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input);
            }
            // 5. 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        result.append(getContent(line));
                    }
                    return result.toString();
                }
            } else {
                System.out.println("Error: HTTP " + responseCode);
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        errorResponse.append(line);
                    }
                    System.out.println("Error Response: " + errorResponse);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
    /**
     * 处理智能体回复内容格式
     * @param jsonStr
     * @return
     */
    public static String getContent(String jsonStr) {
        if (jsonStr == null || !jsonStr.startsWith("data: ") || jsonStr.length() <= 6) {
            return ""; // 空或无效
        }

        // 去除前缀 "data: "
        String pureJson = jsonStr.substring(6);

        JSONObject jsonObject = JSONUtil.parseObj(pureJson);

        return jsonObject
                .getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("delta")
                .getStr("content");
    }
}